package org.phalanx.server.game;

import java.util.ArrayList;
import java.util.Iterator;

import org.phalanx.messenging.AbstractMessage;
import org.phalanx.server.PhalanxServer;
import org.phalanx.server.user.PhalanxUser;

public class PhalanxGameListInfoMessage extends AbstractMessage {
	private ArrayList<PhalanxGameSettings> gameList;
	
	public PhalanxGameListInfoMessage(){
		this.setMessageHeader("gameinfo");
		gameList = new ArrayList<PhalanxGameSettings>();
	}
	
	public void addPhalanxGame(ArrayList<PhalanxGameSettings> gameList){
		this.gameList = gameList;
		serializeGameList();
	}
	
	private void serializeGameList(){
		StringBuffer gameListString = new StringBuffer();
		
		Iterator<PhalanxGameSettings> i = gameList.iterator();
		boolean isFirst = true;
		
		while (i.hasNext()){
			PhalanxGameSettings tempGame = i.next();

			PhalanxUser u = (PhalanxUser)PhalanxServer.getServerInstance().getCacheManager()
			.getElement("UserCache", tempGame.getGameCreatorId());

			if (u != null){
				String userName = u.getUserName();
				
				if (!isFirst){
					gameListString.append(":");
				} else {
					isFirst = false;
				}


				gameListString.append("{");
				gameListString.append(tempGame.getId());
				gameListString.append("!");
				gameListString.append(tempGame.getGameName());
				gameListString.append("!");
				gameListString.append(tempGame.getMapName());
				gameListString.append("!");
				gameListString.append(tempGame.getCurrentTurn());
				gameListString.append("!");
				gameListString.append(userName);
				gameListString.append("!");
				gameListString.append(tempGame.getNumberOfPlayers());
				gameListString.append("!");
				gameListString.append(tempGame.getTurnMode());
				gameListString.append("}");
			}
		}
		
		this.setToMessage("gamelist", gameListString.toString());
	}
}
